<?php

namespace Swoole\Database;

/**
 * PDO数据库封装类
 * @package SwooleExtend
 * @author Tianfeng.Han
 *
 */
class PdoDB extends \PDO {

	public $debug = false;

	protected $config;

	public function __construct($db_config) {
		$this->config = $db_config;
	}

	public function connect() {
		$db_config = &$this->config;
		$dsn = $db_config['dbms'] . ":host=" . $db_config['host'] . ";dbname=" . $db_config['name'];
		
		if (!empty($db_config['persistent'])) {
			parent::__construct($dsn, $db_config['user'], $db_config['passwd'], array(
					\PDO::ATTR_PERSISTENT => true 
			));
		} else {
			parent::__construct($dsn, $db_config['user'], $db_config['passwd']);
		}
		if ($db_config['setname'])
			parent::query('set names ' . $db_config['charset']);
		$this->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
	}

	public function quote($str, $paramtype = NULL) {
		return trim(parent::quote($str, $paramtype), '\'');
	}

	/**
	 * 执行一个SQL语句
	 * @param string $sql 执行的SQL语句
	 * @return \PDOStatement
	 */
	public final function query($sql) {
		if ($this->debug) {
			echo "$sql<br />\n<hr />";
		}
		$res = parent::query($sql) or \Swoole\Error::info("SQL Error", implode(", ", $this->errorInfo()) . "<hr />$sql");
		return $res;
	}

	/**
	 * 执行一个参数化SQL语句,并返回一行结果
	 * @param string $sql 执行的SQL语句
	 * @param  mixed $_     [optional]
	 * @return mixed
	 */
	public final function queryLine($sql, $_) {
		$params = func_get_args();
		if ($this->debug) {
			var_dump($params);
		}
		array_shift($params);
		$stm = $this->prepare($sql);
		if ($stm->execute($params)) {
			$ret = $stm->fetch();
			$stm->closeCursor();
			return $ret;
		} else {
			\Swoole\Error::info("SQL Error", implode(", ", $this->errorInfo()) . "<hr />$sql");
			return false;
		}
	}

	/**
	 * 执行一个参数化SQL语句,并返回所有结果
	 * @param string $sql 执行的SQL语句
	 * @param  mixed $_     [optional]
	 * @return mixed
	 */
	public final function queryAll($sql, $_) {
		$params = func_get_args();
		if ($this->debug) {
			var_dump($params);
		}
		array_shift($params);
		$stm = $this->prepare($sql);
		if ($stm->execute($params)) {
			$ret = $stm->fetchAll();
			$stm->closeCursor();
			return $ret;
		} else {
			\Swoole\Error::info("SQL Error", implode(", ", $this->errorInfo()) . "<hr />$sql");
			return false;
		}
	}

	/**
	 * 执行一个参数化SQL语句
	 * @param string $sql 执行的SQL语句
	 * @param  mixed $_     [optional]
	 * @return int          last insert id
	 */
	public final function execute($sql, $_) {
		$params = func_get_args();
		if ($this->debug) {
			var_dump($params);
		}
		array_shift($params);
		$stm = $this->prepare($sql);
		if ($stm->execute($params)) {
			return $this->lastInsertId();
		} else {
			\Swoole\Error::info("SQL Error", implode(", ", $this->errorInfo()) . "<hr />$sql");
			return false;
		}
	}

	/**
	 * 关闭连接，释放资源
	 * @return null
	 */
	public function close() {
		unset($this);
	}
}
